package com.ruoyi.health.report.service.impl;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.PrimaryKeyIdUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.health.dify.DifyClient;
import com.ruoyi.health.dify.WorkflowResponse;
import com.ruoyi.health.report.domain.*;
import com.ruoyi.health.report.enums.CycleEnum;
import com.ruoyi.health.report.mapper.*;
import com.ruoyi.health.report.service.IHealthReportStatisticsService;
import com.ruoyi.iot.api.RemoteIotService;
import com.ruoyi.iot.api.domain.HealthDatas;
import com.ruoyi.iot.api.domain.HeathParam;
import com.ruoyi.iot.api.domain.TimeValueItem;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.IsoFields;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 健康报告主表Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-25
 */
@Service
public class HealthReportStatisticsServiceImpl implements IHealthReportStatisticsService {
    @Autowired
    private HealthReportStatisticsMapper healthReportStatisticsMapper;

    @Autowired
    private HealthMetricConfigMapper healthMetricConfigMapper;

    @Autowired
    private HealthMetricDataMapper healthMetricDataMapper;

    @Autowired
    private HealthMetricDetailMapper healthMetricDetailMapper;

    @Autowired
    private HealthRiskMapper healthRiskMapper;

    @Autowired
    private HealthSuggestionMapper healthSuggestionMapper;


    @Autowired
    private RemoteIotService remoteIotService;


    @Autowired
    private DifyClient difyClient;

    /**
     * 查询健康报告主表
     *
     * @param id 健康报告主表ID
     * @return 健康报告主表
     */
    @Override
    public HealthReportStatistics selectHealthReportStatisticsById(Long id) {
        return healthReportStatisticsMapper.selectHealthReportStatisticsById(id);
    }

    /**
     * 查询健康报告主表列表
     *
     * @param healthReportStatistics 健康报告主表
     * @return 健康报告主表
     */
    @Override
    public List<HealthReportStatistics> selectHealthReportStatisticsList(HealthReportStatistics healthReportStatistics) {
        return healthReportStatisticsMapper.selectHealthReportStatisticsList(healthReportStatistics);
    }

    /**
     * 新增健康报告主表
     *
     * @param healthReportStatistics 健康报告主表
     * @return 结果
     */
    @Override
    public int insertHealthReportStatistics(HealthReportStatistics healthReportStatistics) {
        return healthReportStatisticsMapper.insertHealthReportStatistics(healthReportStatistics);
    }

    /**
     * 修改健康报告主表
     *
     * @param healthReportStatistics 健康报告主表
     * @return 结果
     */
    @Override
    public int updateHealthReportStatistics(HealthReportStatistics healthReportStatistics) {
        return healthReportStatisticsMapper.updateHealthReportStatistics(healthReportStatistics);
    }

    /**
     * 批量删除健康报告主表
     *
     * @param ids 需要删除的健康报告主表ID
     * @return 结果
     */
    @Override
    public int deleteHealthReportStatisticsByIds(Long[] ids) {
        return healthReportStatisticsMapper.deleteHealthReportStatisticsByIds(ids);
    }

    /**
     * 删除健康报告主表信息
     *
     * @param id 健康报告主表ID
     * @return 结果
     */
    @Override
    public int deleteHealthReportStatisticsById(Long id) {
        return healthReportStatisticsMapper.deleteHealthReportStatisticsById(id);
    }

    /**
     * 根据客户ID和报告类型查询最新的健康报告
     *
     * @param customerId 客户ID
     * @param reportType 报告类型
     * @return 健康报告主表
     */
    @Override
    public HealthReportStatistics selectLatestHealthReportByCustomerAndType(Long customerId, String reportType) {
        return healthReportStatisticsMapper.selectLatestHealthReportByCustomerAndType(customerId, reportType);
    }

    /**
     * 根据客户ID、报告类型和报告周期查询健康报告
     *
     * @param customerId   客户ID
     * @param reportType   报告类型
     * @param reportPeriod 报告周期
     * @return 健康报告主表
     */
    @Override
    public HealthReportStatistics selectHealthReportByCustomerTypeAndPeriod(Long customerId, String reportType, String reportPeriod) {
        return healthReportStatisticsMapper.selectHealthReportByCustomerTypeAndPeriod(customerId, reportType, reportPeriod);
    }

    /**
     * 根据客户ID和报告类型查询可用的报告周期列表
     *
     * @param customerId 客户ID
     * @param reportType 报告类型
     * @return 报告周期列表
     */
    @Override
    public List<String> selectAvailablePeriodsByCustomerAndType(Long customerId, String reportType) {
        return healthReportStatisticsMapper.selectAvailablePeriodsByCustomerAndType(customerId, reportType);
    }

    /**
     * 获取完整健康报告数据
     *
     * @param customerId   客户ID
     * @param reportType   报告类型
     * @param reportPeriod 报告周期
     * @return 完整健康报告数据
     */
    @Override
    public Map<String, Object> getFullHealthReportData(Long customerId, String reportType, String reportPeriod) {
        Map<String, Object> result = new HashMap<>();

        // 获取健康报告主表数据
        HealthReportStatistics report = getReportData(customerId, reportType, reportPeriod);

        if (report == null) {
            // 如果没有数据，返回空结构
            return createEmptyReportData(reportType);
        }

        // 查询健康指标数据
        List<HealthMetricData> metricDataList = healthMetricDataMapper.selectHealthMetricDataListByReportId(report.getId());

        // 查询健康风险数据
        List<HealthRisk> riskList = healthRiskMapper.selectHealthRiskListByReportId(report.getId());

        // 查询健康建议数据
        List<HealthSuggestion> suggestionList = healthSuggestionMapper.selectHealthSuggestionListByReportId(report.getId());

        // 查询所有健康指标配置
        List<HealthMetricConfig> metricConfigList = healthMetricConfigMapper.selectAllHealthMetricConfig();
        Map<String, HealthMetricConfig> metricConfigMap = metricConfigList.stream()
                .collect(Collectors.toMap(HealthMetricConfig::getMetricKey, config -> config));

        // 为每个指标数据填充详细数据和配置信息（使用并行流提高处理效率）
        if (!metricDataList.isEmpty()) {
            metricDataList.parallelStream().forEach(metricData -> {
                // 查询详细数据
                HealthMetricDetail detail = healthMetricDetailMapper.selectHealthMetricDetailListByDataId(metricData.getId());
                metricData.setDetailList(detail);

                // 填充配置信息
                HealthMetricConfig config = metricConfigMap.get(metricData.getMetricKey());
                metricData.setMetricConfig(config);
            });
        }

        // 填充报告对象
        report.setMetricDataList(metricDataList);
        report.setRiskList(riskList);
        report.setSuggestionList(suggestionList);

        // 构建返回数据结构
        result.put("report", report);

        // 基本信息
        Map<String, Object> basicInfo = new HashMap<>();
        basicInfo.put("currentDate", report.getReportPeriod());
        basicInfo.put("avatarUrl", "");
        result.put("basicInfo", basicInfo);

        // 健康评分
        Map<String, Object> healthScore = new HashMap<>();
        healthScore.put("score", report.getHealthScore());
        healthScore.put("text", report.getHealthScoreText());
        healthScore.put("description", report.getHealthScoreDesc());
        result.put("healthScore", healthScore);

        // 健康风险和建议
        result.put("healthRisks", riskList);
        result.put("healthSuggestions", suggestionList);

        // 健康指标配置
        Map<String, Object> healthMetricsConfig = buildHealthMetricsConfig(metricConfigList);
        result.put("healthMetricsConfig", healthMetricsConfig);

        // 健康指标数据
        Map<String, Object> healthMetrics = buildHealthMetrics(metricDataList);
        result.put("healthMetrics", healthMetrics);


        return result;
    }

    /**
     * 获取报告数据
     */
    private HealthReportStatistics getReportData(Long customerId, String reportType, String reportPeriod) {
        if (reportPeriod != null && !reportPeriod.isEmpty()) {
            return healthReportStatisticsMapper.selectHealthReportByCustomerTypeAndPeriod(customerId, reportType, reportPeriod);
        } else {
            return healthReportStatisticsMapper.selectLatestHealthReportByCustomerAndType(customerId, reportType);
        }
    }

    /**
     * 构建健康指标配置
     */
    private Map<String, Object> buildHealthMetricsConfig(List<HealthMetricConfig> metricConfigList) {
        Map<String, Object> healthMetricsConfig = new HashMap<>();

        if (metricConfigList != null) {
            for (HealthMetricConfig config : metricConfigList) {
                Map<String, Object> configMap = new HashMap<>();
                configMap.put("title", config.getMetricName());
                configMap.put("subtitle", config.getMetricSubtitle());
                configMap.put("unit", config.getUnit());
                configMap.put("icon", config.getIcon());
                configMap.put("iconClass", config.getIconClass());
                configMap.put("color", config.getColor());
                if(config.getMetricKey().equals("bloodPressure")){
                    String[] split = config.getColor().split(",");
                    configMap.put("color", split);
                }
                configMap.put("normalRange", config.getNormalRange());

                healthMetricsConfig.put(config.getMetricKey(), configMap);
            }
        }

        return healthMetricsConfig;
    }

    /**
     * 构建健康指标数据
     */
    private Map<String, Object> buildHealthMetrics(List<HealthMetricData> metricDataList) {
        Map<String, Object> healthMetrics = new HashMap<>();

        if (metricDataList != null) {
            for (HealthMetricData metricData : metricDataList) {
                HealthMetricConfig config = metricData.getMetricConfig();
                if (config == null) continue;

                Map<String, Object> metricMap = new HashMap<>();
                metricMap.put("average", metricData.getAverageValue());
                metricMap.put("status", metricData.getStatusText());
                metricMap.put("statusClass", metricData.getStatusClass());
                metricMap.put("statusIcon", metricData.getStatusIcon());
                metricMap.put("info", metricData.getInfo());
                metricMap.put("recommendations", metricData.getRecommendations());

                // 构建数据部分
                Map<String, Object> dataMap = buildMetricData(metricData, config);
                metricMap.put("data", dataMap);
                healthMetrics.put(config.getMetricKey(), metricMap);
            }
        }

        return healthMetrics;
    }

    /**
     * 构建指标数据部分
     */
    private Map<String, Object> buildMetricData(HealthMetricData metricData, HealthMetricConfig config) {
        Map<String, Object> dataMap = new HashMap<>();

        HealthMetricDetail detail = metricData.getDetailList();
        if (detail != null && detail.getDetailStr() != null) {
            List<String> labels = new ArrayList<>();
            List<Object> values = new ArrayList<>();
            List<Object> systolicValues = new ArrayList<>();
            List<Object> diastolicValues = new ArrayList<>();
            List<Object> deepValues = new ArrayList<>();
            List<Object> lightValues = new ArrayList<>();
            List<Object> awakeValues = new ArrayList<>();

            try {
                List<JSONObject> jsonObjects = JSONArray.parseArray(detail.getDetailStr(), JSONObject.class);
                if (jsonObjects != null) {
                    for (JSONObject obj : jsonObjects) {
                        String label = obj.getString("label");
                        if (label != null) {
                            labels.add(label);
                        }

                        String value1 = obj.getString("value1");
                        if (value1 != null) {
                            values.add(value1);
                        }

                        String value2 = obj.getString("value2");
                        if (value2 != null) {
                            if ("bloodPressure".equals(config.getMetricKey())) {
                                String systolic = obj.getString("value1");
                                if (systolic != null) {
                                    systolicValues.add(systolic);
                                }
                                diastolicValues.add(value2);
                            } else if ("sleep".equals(config.getMetricKey())) {
                                String deepValue = obj.getString("value1");
                                if (deepValue != null) {
                                    deepValues.add(deepValue);
                                }
                                lightValues.add(value2);

                                String value3 = obj.getString("value3");
                                if (value3 != null) {
                                    awakeValues.add(value3);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                // 处理JSON解析异常
                e.printStackTrace();
            }

            dataMap.put("labels", labels);
            if (!values.isEmpty()) dataMap.put("values", values);
            if (!systolicValues.isEmpty()) dataMap.put("systolic", systolicValues);
            if (!diastolicValues.isEmpty()) dataMap.put("diastolic", diastolicValues);
            if (!deepValues.isEmpty()) dataMap.put("deep", deepValues);
            if (!lightValues.isEmpty()) dataMap.put("light", lightValues);
            if (!awakeValues.isEmpty()) dataMap.put("awake", awakeValues);
        }

        return dataMap;
    }


    /**
     * 创建空报告数据结构
     *
     * @param reportType 报告类型
     * @return 空报告数据
     */
    private Map<String, Object> createEmptyReportData(String reportType) {
        Map<String, Object> result = new HashMap<>();

        // 基本信息
        Map<String, Object> basicInfo = new HashMap<>();
        basicInfo.put("currentDate", "暂无数据");
        basicInfo.put("avatarUrl", "");
        result.put("basicInfo", basicInfo);

        // 健康评分
        Map<String, Object> healthScore = new HashMap<>();
        healthScore.put("score", 0);
        healthScore.put("text", "暂无评分");
        healthScore.put("description", "暂无数据");
        result.put("healthScore", healthScore);

        // 健康风险
        result.put("healthRisks", new ArrayList<>());

        // 健康建议
        result.put("healthSuggestions", new ArrayList<>());

        // 健康指标配置
        Map<String, Object> healthMetricsConfig = new HashMap<>();
        // 添加默认配置
        addDefaultMetricConfig(healthMetricsConfig, "heartRate", "心率", "每分钟心跳次数", "bpm", "60-100", "fa fa-heartbeat", "heart-rate", "#165DFF");
        addDefaultMetricConfig(healthMetricsConfig, "bloodPressure", "血压", "收缩压/舒张压", "mmHg", "收缩压<130，舒张压<80", "fa fa-tint", "blood-pressure", "#F87272,#FB923C");
        addDefaultMetricConfig(healthMetricsConfig, "bloodSugar", "血糖", "空腹测量值", "mmol/L", "3.9-6.1", "fa fa-flask", "blood-sugar", "#36D399");
        addDefaultMetricConfig(healthMetricsConfig, "oxygenLevel", "血氧", "血液氧饱和度", "%", "95-100", "fa fa-moon-o", "oxygen-level", "#36D399");
        addDefaultMetricConfig(healthMetricsConfig, "sleep", "睡眠", "睡眠时长与质量", "小时", "7-8", "fa fa-bed", "sleep", "#FB923C");
        addDefaultMetricConfig(healthMetricsConfig, "steps", "步数", "每日行走步数", "步", "8000-10000", "fa fa-male", "steps", "#165DFF");
        result.put("healthMetricsConfig", healthMetricsConfig);

        // 健康指标数据
        Map<String, Object> healthMetrics = new HashMap<>();
        addEmptyMetricData(healthMetrics, "heartRate", "0", "暂无数据", "status-empty", "fa fa-exclamation-circle", "暂无心率数据", "暂无心率数据");
        addEmptyMetricData(healthMetrics, "bloodPressure", "0/0", "暂无数据", "status-empty", "fa fa-exclamation-circle", "暂无血压数据", "暂无血压数据");
        addEmptyMetricData(healthMetrics, "bloodSugar", "0", "暂无数据", "status-empty", "fa fa-exclamation-circle", "暂无血糖数据", "暂无血糖数据");
        addEmptyMetricData(healthMetrics, "oxygenLevel", "0", "暂无数据", "status-empty", "fa fa-exclamation-circle", "暂无血氧数据", "暂无血氧数据");
        addEmptyMetricData(healthMetrics, "sleep", "0", "暂无数据", "status-empty", "fa fa-exclamation-circle", "暂无睡眠数据", "暂无睡眠数据");
        addEmptyMetricData(healthMetrics, "steps", "0", "暂无数据", "status-empty", "fa fa-exclamation-circle", "暂无步数数据", "暂无步数数据");
        result.put("healthMetrics", healthMetrics);


        return result;
    }

    /**
     * 添加默认指标配置
     */
    private void addDefaultMetricConfig(Map<String, Object> configMap, String key, String name, String subtitle,
                                        String unit, String normalRange, String icon, String iconClass, String color) {
        Map<String, Object> config = new HashMap<>();
        config.put("title", name);
        config.put("subtitle", subtitle);
        config.put("unit", unit);
        config.put("normalRange", normalRange);
        config.put("icon", icon);
        config.put("iconClass", iconClass);
        config.put("color", color);
        configMap.put(key, config);
    }

    /**
     * 添加空指标数据
     */
    private void addEmptyMetricData(Map<String, Object> metricsMap, String key, String average, String status,
                                    String statusClass, String statusIcon, String info, String recommendations) {
        Map<String, Object> metric = new HashMap<>();
        metric.put("average", average);
        metric.put("status", status);
        metric.put("statusClass", statusClass);
        metric.put("statusIcon", statusIcon);
        metric.put("info", info);
        metric.put("recommendations", recommendations);

        Map<String, Object> data = new HashMap<>();
        data.put("labels", new ArrayList<>());
        data.put("values", new ArrayList<>());
        metric.put("data", data);

        metricsMap.put(key, metric);
    }

    @Override
    public Map<String, List<Map<String, Object>>> getTimeBaseData(Long customerId, String timeType, Map<String, String> param) {
        Map<String, List<Map<String, Object>>> result = new HashMap<>();
        List<Map<String, Object>> arrayList = new ArrayList<>();
        result.put("baseHealthData", arrayList);

        Map<String, Object> params = new HashMap<>();
        params.put("customerId", customerId);
        params.put("reportType", CycleEnum.DAILY.getValue());

        if ("7days".equals(timeType)) {
            Date date = DateUtils.addDays(DateUtils.getNowDate(), -7);
            params.put("startDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
        } else if ("30days".equals(timeType)) {
            Date date = DateUtils.addDays(DateUtils.getNowDate(), -30);
            params.put("startDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
        } else if ("3months".equals(timeType)) {
            Date date = DateUtils.addMonths(DateUtils.getNowDate(), -3);
            params.put("startDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
        } else if ("1year".equals(timeType)) {
            Date date = DateUtils.addYears(DateUtils.getNowDate(), -1);
            params.put("startDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
        }

        List<HealthReportStatistics> reports = healthReportStatisticsMapper.selectReport(params);
        List<HealthMetricConfig> metricConfigList = healthMetricConfigMapper.selectAllHealthMetricConfig();
        List<Map<String, Object>> metricConfigs = new ArrayList<>();
        result.put("metricConfigs", metricConfigs);
        if (reports == null || reports.size() == 0) {
            for (HealthMetricConfig config : metricConfigList) {
                Map<String, Object> metricMap = new HashMap<>();
                ;
                metricMap.put("key", config.getMetricKey());
                metricMap.put("name", config.getMetricName());
                metricMap.put("type", "status-success");
                metricMap.put("icon", config.getIcon());
                metricMap.put("iconClass", config.getIconClass());
                metricMap.put("normalRange", config.getNormalRange());
                metricMap.put("recommendations", null);
                metricMap.put("unit", config.getUnit());
                metricMap.put("average", null);
                metricConfigs.add(metricMap);
            }
            return result;
        }

       // reports.sort((o1, o2) -> o1.getReportDate().compareTo(o2.getReportDate()));

        // 一次性获取所有报告的指标数据
        List<Long> reportIds = reports.stream().map(HealthReportStatistics::getId).collect(Collectors.toList());
        List<HealthMetricData> allMetricDataList = healthMetricDataMapper.selectHealthMetricDataListByReportIds(reportIds);

        // 按reportId分组指标数据
        Map<Long, List<HealthMetricData>> metricDataByReportId = allMetricDataList.stream()
                .collect(Collectors.groupingBy(HealthMetricData::getReportId));

        // 一次性获取所有报告的建议数据
        List<HealthSuggestion> allSuggestionList = healthSuggestionMapper.selectHealthSuggestionListByReportIds(reportIds);

        // 按reportId分组建议数据
        Map<Long, List<HealthSuggestion>> suggestionByReportId = allSuggestionList.stream()
                .collect(Collectors.groupingBy(HealthSuggestion::getReportId));


        for (int i = 0; i < reports.size(); i++) {
            HealthReportStatistics report = reports.get(i);
            Map<String, Object> item = new HashMap<>();
            item.put("dateValue", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, report.getReportDate()));
            item.put("date", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, report.getReportDate()));
            item.put("score", report.getHealthScore());

            Map<String, Object> event = new HashMap<>();
            event.put("title", "健康状况" + report.getHealthScoreText());
            event.put("description", report.getHealthScoreDesc());
            item.put("event", event);

            List<Map<String, Object>> temp = new ArrayList<>();
            item.put("metrics", temp);

            // 从分组数据中获取当前报告的指标数据
            List<HealthMetricData> metricDataList = metricDataByReportId.getOrDefault(report.getId(), new ArrayList<>());
            Map<String, HealthMetricData> metricDataMap = metricDataList.stream()
                    .collect(Collectors.toMap(HealthMetricData::getMetricKey, data -> data));

            for (HealthMetricConfig config : metricConfigList) {
                HealthMetricData healthMetricData = metricDataMap.get(config.getMetricKey());
                if (healthMetricData == null) {
                    continue;
                }
                Map<String, Object> metrics = new HashMap<>();
                metrics.put("name", config.getMetricName());
                metrics.put("key", config.getMetricKey());

                String averageValue = healthMetricData.getAverageValue();
                metrics.put("value", averageValue);
                if ("bloodPressure".equals(config.getMetricKey())) {
                    String[] split = averageValue.split("/");
                    metrics.put("systolic", split[0]);
                    metrics.put("diastolic", split[1]);
                }
                // 计算change值
                Object change = calculateChangeValue(config.getMetricKey(), healthMetricData, i, reports, metricDataByReportId);
                metrics.put("change", change);
                metrics.put("unit", config.getUnit());
                metrics.put("trend",  getTrendValue(change));
                metrics.put("status", healthMetricData.getStatusText());
                temp.add(metrics);
                getStringObjectMap(metricConfigs, config, healthMetricData);
            }
            item.put("notes", report.getHealthScoreDesc());

            // 从分组数据中获取当前报告的建议数据
            List<HealthSuggestion> suggestionList = suggestionByReportId.getOrDefault(report.getId(), new ArrayList<>());
            if (!suggestionList.isEmpty()) {
                List<String> collect = suggestionList.stream().map(suggestion -> {
                    return suggestion.getSuggestionTitle() + ":" + suggestion.getSuggestionDescription();
                }).collect(Collectors.toList());
                item.put("recommendations", collect);
            } else {
                item.put("recommendations", Collections.EMPTY_LIST);
            }
            arrayList.add(item);
        }
        //arrayList.sort((o1, o2) -> DateUtils.parseDate(o2.get("dateValue")).compareTo(DateUtils.parseDate(o1.get("dateValue"))));
        return result;
    }


    /**
     * 计算指标变化值
     *
     * @param metricKey            指标键
     * @param currentMetricData    当前指标数据
     * @param currentIndex         当前报告索引
     * @param reports              报告列表
     * @param metricDataByReportId 按报告ID分组的指标数据
     * @return 变化值
     */
    private Object calculateChangeValue(String metricKey, HealthMetricData currentMetricData,
                                        int currentIndex, List<HealthReportStatistics> reports,
                                        Map<Long, List<HealthMetricData>> metricDataByReportId) {
        // 如果是第一个报告或者没有前一个报告的数据，则变化值为0
        if (currentIndex <= 0) {
            return 0;
        }

        try {
            // 获取前一个报告
            HealthReportStatistics previousReport = reports.get(currentIndex - 1);
            List<HealthMetricData> previousMetricDataList = metricDataByReportId.getOrDefault(
                    previousReport.getId(), new ArrayList<>());

            // 查找前一个报告中相同指标的数据
            HealthMetricData previousMetricData = null;
            for (HealthMetricData data : previousMetricDataList) {
                if (metricKey.equals(data.getMetricKey())) {
                    previousMetricData = data;
                    break;
                }
            }

            // 如果前一个报告中没有该指标数据，则变化值为0
            if (previousMetricData == null) {
                return 0;
            }

            // 根据指标类型解析数值并计算差值
            if ("bloodPressure".equals(metricKey)) {
                // 血压需要特殊处理，包含收缩压和舒张压
                String[] currentValues = currentMetricData.getAverageValue().split("/");
                String[] previousValues = previousMetricData.getAverageValue().split("/");

                if (currentValues.length >= 2 && previousValues.length >= 2) {
                    int currentSystolic = Integer.parseInt(currentValues[0]);
                    int previousSystolic = Integer.parseInt(previousValues[0]);
                    return currentSystolic - previousSystolic;
                }
            } else {
                // 其他指标处理
                double currentValue = Double.parseDouble(currentMetricData.getAverageValue());
                double previousValue = Double.parseDouble(previousMetricData.getAverageValue());
                return Math.round((currentValue - previousValue) * 100.0) / 100.0; // 保留两位小数
            }
        } catch (Exception e) {
            // 解析异常时返回0
            return 0;
        }

        return 0;
    }

    /**
     * 根据变化值确定趋势
     *
     * @param change 变化值
     * @return 趋势字符串
     */
    private String getTrendValue(Object change) {
        if (change instanceof Number) {
            double value = ((Number) change).doubleValue();
            if (value > 0) {
                return "up";
            } else if (value < 0) {
                return "down";
            }
        }
        return "stable";
    }


    @NotNull
    private static void getStringObjectMap(List<Map<String, Object>> list, HealthMetricConfig config, HealthMetricData healthMetricData) {
        Map<String, Object> metricConfig = null;
        Optional<Map<String, Object>> optional = list.stream()
                .filter(item -> config.getMetricKey().equals(item.get("key")))
                .findFirst();
        if (optional.isPresent()) {
            metricConfig = optional.get();
        } else {
            metricConfig = new HashMap();
            list.add(metricConfig);
        }

        metricConfig.put("key", config.getMetricKey());
        metricConfig.put("name", config.getMetricName());
        metricConfig.put("type", "status-success".equals(healthMetricData.getStatusClass()) ? "primary" : "warning");
        metricConfig.put("icon", config.getIcon());
        metricConfig.put("iconClass", config.getIconClass());
        metricConfig.put("normalRange", config.getNormalRange());
        metricConfig.put("recommendations", healthMetricData.getRecommendations());
        metricConfig.put("unit", config.getUnit());
        metricConfig.put("average", healthMetricData.getAverageValue());
    }

    @Override
    public void createHealthReportByDay(Date nowDate) {
        //获取当前没有生成报告的用户
        String period = DateUtils.parseDateToStr("YYYY-MM-dd", DateUtils.addDays(nowDate, -1));
        List<Long> customerIds = healthReportStatisticsMapper.getIncompleteCustomer("daily", period);
        if(customerIds.isEmpty()){
            return;
        }
        String reportType="daily";
        Date reportDate=DateUtils.addDays(nowDate, -1);
        customerIds.forEach(customerId -> {
            HeathParam heathParam = new HeathParam();
            heathParam.setDate(nowDate);
            heathParam.setCustomerId(customerId);



            R<HealthDatas> healthDataInner = remoteIotService.getHealthDataInner(heathParam, SecurityConstants.INNER);
            createReport(healthDataInner,customerId, reportType, period, reportDate);
        });

    }


    private void createReport(R<HealthDatas> healthDataInner,Long customerId,  String reportType, String period, Date reportDate) {
        if (StringUtils.isNotNull(healthDataInner) && StringUtils.isNotNull(healthDataInner.getData())) {
            HealthDatas data = healthDataInner.getData();
            String dataStr = JSONObject.toJSONString(data);
            //调用dify获取结果
            WorkflowResponse workflow = difyClient.runWorkflow(dataStr,"daily".equals(reportType)?"1":"weekly".equals(reportType)?"2":"3");
            if ("succeeded".equals(workflow.getData().getStatus())) {
                String resultInf = workflow.getData().getOutputs().get("text");
                HealthResultVO resultVO = JSONObject.parseObject(resultInf, HealthResultVO.class);
                HealthReportStatistics report = new HealthReportStatistics();
                //查看当前用户是否已经有创建过period报告
                report.setCustomerId(customerId);
                report.setReportType(reportType);
                report.setReportPeriod(period);
                report.setReportDate(reportDate);
                report.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                report.setCreateTime(DateUtils.getNowDate());
                report.setStatus("3");
                report.setHealthScore(resultVO.getHealthScore());
                report.setHealthScoreDesc(resultVO.getHealthScoreDesc());
                report.setHealthScoreText(resultVO.getHealthScoreText());
                healthReportStatisticsMapper.insertHealthReportStatistics(report);
                List<HealthMetricData> healthMetricDatas = new ArrayList<>();
                List<HealthMetricDetail> healthMetricDetails = new ArrayList<>();

                //血压
                HealthMetricData bloodPressure = resultVO.getBloodPressure();
                List<TimeValueItem> bloodPressures = data.getBloodPressures();
                String jsonString = JSONArray.toJSONString(bloodPressures);
                bloodPressure.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                bloodPressure.setReportId(report.getId());
                healthMetricDatas.add(bloodPressure);

                HealthMetricDetail bloodPressureDetail = new HealthMetricDetail();
                bloodPressureDetail.setDataId(bloodPressure.getId());
                bloodPressureDetail.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                bloodPressureDetail.setDetail(jsonString.getBytes());
                healthMetricDetails.add(bloodPressureDetail);

                //血糖
                HealthMetricData bloodSugar = resultVO.getBloodSugar();
                List<TimeValueItem> bloodSugars = data.getBloodSugars();
                String jsonString1 = JSONArray.toJSONString(bloodSugars);
                bloodSugar.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                bloodSugar.setReportId(report.getId());
                healthMetricDatas.add(bloodSugar);

                HealthMetricDetail healthMetricDetail = new HealthMetricDetail();
                healthMetricDetail.setDataId(bloodSugar.getId());
                healthMetricDetail.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                healthMetricDetail.setDetail(jsonString1.getBytes());
                healthMetricDetails.add(healthMetricDetail);

                //心率
                HealthMetricData heartRate = resultVO.getHeartRate();
                List<TimeValueItem> heartRates = data.getHeartRates();
                String jsonString2 = JSONArray.toJSONString(heartRates);
                heartRate.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                heartRate.setReportId(report.getId());
                healthMetricDatas.add(heartRate);

                HealthMetricDetail heartRateDetail = new HealthMetricDetail();
                heartRateDetail.setDataId(heartRate.getId());
                heartRateDetail.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                heartRateDetail.setDetail(jsonString2.getBytes());
                healthMetricDetails.add(heartRateDetail);

                //血氧
                HealthMetricData oxygenLevel = resultVO.getOxygenLevel();
                List<TimeValueItem> oxygenLevels = data.getOxygens();
                String jsonString3 = JSONArray.toJSONString(oxygenLevels);
                oxygenLevel.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                oxygenLevel.setReportId(report.getId());
                healthMetricDatas.add(oxygenLevel);

                HealthMetricDetail oxygenLevelDetail = new HealthMetricDetail();
                oxygenLevelDetail.setDataId(oxygenLevel.getId());
                oxygenLevelDetail.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                oxygenLevelDetail.setDetail(jsonString3.getBytes());
                healthMetricDetails.add(oxygenLevelDetail);

                //disk
                List<HealthRisk> risks = resultVO.getRisk();
                for (int i = 0; i < risks.size(); i++) {
                    HealthRisk risk = risks.get(i);
                    risk.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                    risk.setReportId(report.getId());
                    risk.setSortOrder((long) i);
                }

                //suggestion
                List<HealthSuggestion> suggestions = resultVO.getSuggestion();

                for (int i = 0; i < suggestions.size(); i++) {
                    HealthSuggestion suggestion = suggestions.get(i);
                    suggestion.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                    suggestion.setReportId(report.getId());
                    suggestion.setSortOrder((long) i);
                }


                healthMetricDataMapper.batchInsertHealthMetricData(healthMetricDatas);
                healthMetricDetailMapper.batchInsertHealthMetricDetail(healthMetricDetails);
                healthRiskMapper.batchInsertHealthRisk(risks);
                healthSuggestionMapper.batchInsertHealthSuggestion(suggestions);
            }
        }
    }

    @Override
    public void createHealthReportByWeek(Date nowDate) {
        String period = getWeekOfYear(nowDate);
        List<Long> customerIds = healthReportStatisticsMapper.getIncompleteCustomer("weekly", period);
        if(customerIds.isEmpty()){
            return;
        }
        String reportType="weekly";
        customerIds.forEach(customerId -> {
            HeathParam heathParam = new HeathParam();
            heathParam.setDate(nowDate);
            heathParam.setCustomerId(customerId);
            R<HealthDatas> healthDataInner = remoteIotService.getLastWeekHealthDataInner(heathParam, SecurityConstants.INNER);
            createReport(healthDataInner,customerId, reportType, period, nowDate);
        });
    }

    @Override
    public void createHealthReportByMonth(Date nowDate) {
        String period = DateUtils.parseDateToStr(DateUtils.YYYY_MM,DateUtils.addMonths(nowDate, -1));
        List<Long> customerIds = healthReportStatisticsMapper.getIncompleteCustomer("monthly", period);
        if(customerIds.isEmpty()){
            return;
        }
        String reportType="monthly";
        customerIds.forEach(customerId -> {
            HeathParam heathParam = new HeathParam();
            heathParam.setDate(nowDate);
            heathParam.setCustomerId(customerId);
            R<HealthDatas> healthDataInner = remoteIotService.getLastMonthHealthDataInner(heathParam, SecurityConstants.INNER);
            createReport(healthDataInner,customerId, reportType, period, nowDate);
        });
    }


    public static String getWeekOfYear(Date date) {
        if (date == null) {
            throw new IllegalArgumentException("Date cannot be null");
        }

        // 1. 将 Date 转为 LocalDate（使用系统时区，如 Asia/Shanghai）
        LocalDate localDate = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        // 2. 减去 7 天，得到上周的同一天
        LocalDate lastWeekDate = localDate.minusWeeks(1);

        // 3. 获取 ISO 周年 和 周数
        int weekBasedYear = lastWeekDate.get(IsoFields.WEEK_BASED_YEAR);
        int weekOfWeekBasedYear = lastWeekDate.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);

        // 4. 格式化为 "YYYY-Www"
        return String.format("%d-W%02d", weekBasedYear, weekOfWeekBasedYear);
    }

}
